package com.fand.stater.autoconfigure;

import javax.annotation.Resource;

import com.fand.stater.autoconfigure.properties.ConsumerConfig;
import com.fand.stater.autoconfigure.properties.ProducerConfigure;
import com.fand.stater.listener.MQConsumerLoadEvent;
import com.fand.stater.listener.SysUserESIndexRecordListenter;
import com.fand.stater.listener.SysUserESOperateRecordListenter;
import com.fand.stater.process.RocketMQProcessor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/26
 * Version: 1.0
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(value = {ProducerConfigure.class,ConsumerConfig.class})
@ConditionalOnProperty(value = "rocketmq.enable",havingValue="true",matchIfMissing = false)
public class RocketMqAutoConfiguration {

    @Resource
    private ProducerConfigure producerConfigure;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 创建普通消息发送者实例
     *
     * @return
     * @throws MQClientException
     */
    @SneakyThrows
    @Bean
    public DefaultMQProducer defaultProducer() {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(producerConfigure.getGroupName());
        defaultMQProducer.setNamesrvAddr(producerConfigure.getNamesrvAddr());
        defaultMQProducer.setSendMsgTimeout(producerConfigure.getSendMsgTimeOut());
        defaultMQProducer.setVipChannelEnabled(false);
        defaultMQProducer.setRetryTimesWhenSendFailed(producerConfigure.getRetryTimesWhenSendFailed());
        defaultMQProducer.setMaxMessageSize(producerConfigure.getMaxMessageSize());
        defaultMQProducer.setAsyncSenderExecutor(threadPoolTaskExecutor.getThreadPoolExecutor());
        defaultMQProducer.start();
        return defaultMQProducer;
    }


    @Bean
    public RocketMQProcessor rocketMQProcessor(){
        return new RocketMQProcessor();
    }

    @Bean
    public MQConsumerLoadEvent mqConsumerLoadEvent(){
        return new MQConsumerLoadEvent();
    }

    @Bean
    public SysUserESIndexRecordListenter sysUserESIndexRecordListenter(){
        return new SysUserESIndexRecordListenter();
    }

    @Bean
    public SysUserESOperateRecordListenter sysUserESOperateRecordListenter(){
        return new SysUserESOperateRecordListenter();
    }

}
